package ma.myschool.app.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.faces.context.FacesContext;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

public class CommonUtils {

	public static StreamedContent getBytesFromFile(File file) {
		try (InputStream is = new FileInputStream(file);){
			
	
//			// Create the byte array to hold the data
//			byte[] bytes = new byte[(int)file.length()];
//	
//			// Read in the bytes
//			int offset = 0;
//			int numRead = 0;
//			while (offset < bytes.length
//					&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
//				offset += numRead;
//			}
//	
//			// Ensure all the bytes have been read in
//			if (offset < bytes.length) {
//				throw new IOException("Could not completely read file "+ file.getName());
//			}
//	
//			// Close the input stream and return bytes
//			is.close();
			StreamedContent  image = new DefaultStreamedContent(is,"image/jpeg");
			return image;
		} catch (Exception e) {
			return null;
		}
	}

	public static String getImageFromFile(String image) {
		try{
			if(image != null){
				//retrieve the file data
				File file = new File(image);
				InputStream stream = new FileInputStream(file);
				
				//write the file to the file specified
				String uploadDir = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources");
		        // The following seems to happen when running jetty:run
		        if (uploadDir == null) {
		            uploadDir = new File("src/main/webapp/resources").getAbsolutePath();
		        }
		        uploadDir += "/eleves/";
		        
		        // Create the directory if it doesn't exist
		        File dirPath = new File(uploadDir);

		        if (!dirPath.exists()) {
		            dirPath.mkdirs();
		        }
		        
				OutputStream bos = new FileOutputStream(uploadDir + file.getName());
				int bytesRead;
				byte[] buffer = new byte[8192];
				
				while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
					bos.write(buffer, 0, bytesRead);
				}
				
				bos.close();
				
				//close the stream
				stream.close();
				
				return "/resources/eleves/" + file.getName();
			}
		}catch(Exception exception){}
		
		return "/images/unknown.png";
	}
	
}
